import router from '@/router'
import store from '@/store'
import { Notify } from 'vant'
import { getToken, getPageTitle } from './auth'
// import { judgeBrowser } from '@/utils/index.js'
// import { inDingTalk, hideHeaderNav } from '@/utils/dd'

// 白名单列表
const whiteList = []
router.options.routes.forEach(item => {
  if (item.children !== undefined) {
    item.children.forEach(items => {
      if (!items.meta.permission) {
        whiteList.push(items.path)
      }
    })
  } else {
    if (!item.meta.permission) {
      whiteList.push(item.path)
    }
  }
})

// 路由守卫
router.beforeEach(async(to, from, next) => {
  // 设置页面标题
  document.title = getPageTitle(to.meta.title)
  // determine whether the user has logged in
  const hasToken = getToken()
  if (hasToken) {
    if (to.path === '/login') {
      // 已经登录，跳转到首页
      next({ path: '/' })
    } else {
      // 获取用户信息
      const hasGetUserInfo = store.getters.userInfo
      if (hasGetUserInfo) {
        next()
      } else {
        try {
          // get user info
          store.dispatch('user/GetUserInfo').then(res => {
            next()
          }, () => {
            store.dispatch('user/Loginout')
            next(`/login?redirect=${to.fullPath}`)
          })
        } catch (error) {
          // 清除用户信息，退出登录，跳转登录页
          store.dispatch('user/Loginout')
          Notify.error(error || 'Has Error')
          next(`/login?redirect=${to.fullPath}`)
        }
      }
    }
  } else {
    /* has no token */
    if (whiteList.indexOf(to.path) !== -1) { // 白名单中，无需验证
      next()
    } else {
      // other pages that do not have permission to access are redirected to the login page.
      next(`/login?redirect=${to.fullPath}`)
    }
  }
})

router.afterEach((to, from) => {
  // const browserInfo = judgeBrowser()
  // // 判断是否为手机端
  // if (browserInfo.isMobile) { // 是
  //   // 隐藏钉钉自身的顶部导航栏
  //   if (inDingTalk()) {
  //     hideHeaderNav()
  //   }
  // }
})
